// 路由鉴权
import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from '@/store/modules/user'

// 路由白名单
const whiteRoute: string[] = ['/login']

// 前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  // 用户token
  const userStore = useUserStore(pinia)
  const token = userStore.token
  const name = userStore.name
  nprogress.start()
  if (token) {
    // 用户已登录
    if (to.path === '/login') {
      // 登录后禁止访问login 指向首页
      next({ path: '/' })
    } else {
      if (name) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (err) {
          // 退出登录
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    // 用户未登录
    if (whiteRoute.includes(to.path)) {
      // 在路由白名单内
      next()
    } else {
      // 转回登录页
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
